package com.yt.system.service.impl;

import com.yt.system.dao.*;
import com.yt.system.domain.*;
import com.yt.system.service.ClockService;
import com.yt.system.service.VacateService;
import org.apache.ibatis.annotations.Case;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class ClockServiceImpl implements ClockService {

    @Autowired
    ClockMapper checkMapper;

    @Autowired
    LeavetimeMapper leavetimeMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    VacateMapper vacateMapper;

    @Autowired
    AccountMapper accountMapper;

    @Autowired
    HistoryMapper historyMapper;

    @Autowired
    ScoreMapper scoreMapper;

    /**
     * 早上上班签到
     * @param uid
     * @return
     */
    @Override
    public int clockIn(Integer uid) {
        // new Date()为获取当前系统时间，也可使用当前时间戳
        Date now_time = new Date();

        // 判断是否已签到
        Clock clock = checkMapper.selectByKeyAndTime(uid);
        System.out.println(clock);
        if (clock != null && clock.getEntertime() != null){
            System.out.println("用户已签过到，请勿重复！");
            return 0;
        } else {
            Clock check = new Clock();
            check.setUid(uid);

            //设置日期格式
            SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String enter_time = df1.format(now_time);
            check.setEntertime(enter_time);
            if (now_time.getHours()<8 || (now_time.getHours()==8 && now_time.getMinutes()<=30)){
                check.setCstatus(0);
                check.setCflag(0);
            }else {
                check.setCstatus(1);
                check.setCflag(0);
            }

            System.out.println("签到成功！");
            return checkMapper.insert(check);
        }
    }

    /**
     * 下班打卡
     * @param uid
     * @return
     * @throws ParseException
     */
    @Override
    public int clockOut(Integer uid) throws ParseException {
        // new Date()为获取当前系统时间，也可使用当前时间戳
        Date now_time = new Date();

        //根据cid查找相关考勤信息
        Clock clock = checkMapper.selectByKeyAndTime(uid);
        if (clock == null){
            clock.setUid(uid);
            clock.setCstatus(1);
            clock.setCflag(0);
            checkMapper.insert(clock);
            clock = checkMapper.selectByKeyAndTime(uid);
        } else if (clock.getLeavetime() != null && !clock.getLeavetime().equals("")) {
            System.out.println("用户已签退到，请勿重复！");
            return 0;
        }

        //设置日期格式
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String leave_time = df1.format(now_time);
        clock.setLeavetime(leave_time);

        //获取下班时间
        SimpleDateFormat df2 = new SimpleDateFormat("HH:mm:ss");
        Leavetime leavetime = leavetimeMapper.selectByPrimaryKey(1);
        Date ltime = df2.parse(leavetime.getLtime());

        //判断并修改考勤状态
        if (clock.getCstatus()!=3 && (now_time.getHours()<ltime.getHours() || (now_time.getHours()==ltime.getHours() && now_time.getMinutes()<=ltime.getMinutes()))){
            clock.setCflag(0);
            switch (clock.getCstatus()){
                case 0:
                    clock.setCstatus(2);
                    break;
                case 1:
                    clock.setCstatus(4);
                    break;
                case 4:
                    break;
                default:
                    clock.setCstatus(2);
            }
        }

        System.out.println("签退成功！");
        return checkMapper.updateByPrimaryKeySelective(clock);
    }

    /**
     * 查询所有签到信息
     * @return
     */
    @Override
    public List<Clock> findAllByClock(Clock clock) {
        return checkMapper.selectAllByClock(clock);
    }

    /**
     * 根据用户名name查询考勤信息
     * @param name
     * @return
     */
    @Override
    public List<Clock> findAllClockOrName(String name) {
        if (name != null){
            return checkMapper.selectAllClockOrName(name);
        }else {
            return null;
        }
    }

    /**
     * 根据Uid查询所有签到信息
     * @return
     */
    @Override
    public List<Clock> findAllClockByUid(Integer uid) {
        return checkMapper.selectAllClockByUid(uid);
    }

    /**
     * 更新下班时间
     * @param leave_time
     * @return
     */
    @Override
    public int updateLeaveTime(String leave_time) {
//        //设置日期格式
//        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String time = df1.format(leave_time);
        Leavetime leavetime = new Leavetime();
        leavetime.setLid(1);
        leavetime.setLtime(leave_time);
        return leavetimeMapper.updateByPrimaryKey(leavetime);
    }

    /**
     * 管理员添加考勤信息
     * @param clock
     * @return
     */
    @Override
    public int insertClock(Clock clock) {
        if (clock != null){
            return checkMapper.insert(clock);
        }else {
            return 0;
        }
    }

    /**
     * 管理删除考勤信息
     * @param cid
     * @return
     */
    @Override
    public int deleteClock(Integer cid) {
        if (cid != null) {
            return checkMapper.deleteByPrimaryKey(cid);
        } else {
            return 0;
        }
    }

    /**
     * 管理员更新考勤信息
     * @param clock
     * @return
     */
    @Override
    public int updateClock(Clock clock) {
        if (clock != null){
            return checkMapper.updateByPrimaryKeySelective(clock);
        } else {
            return 0;
        }
    }

    /**
     * 定时周一到周五晚上完善打卡
     */
    @Scheduled(cron = "0 55 23 ? * MON-FRI")
    @Async
    public void night(){
        // new Date()为获取当前系统时间，也可使用当前时间戳
        Date now_date = new Date();

        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String time = df.format(now_date);

        // 查找未签到的人员并做相关操作
        List<User> users = userMapper.findNoClockUserByTime();
        for (User u : users){
            Clock clock = new Clock();
            int uid = u.getUid();
            clock.setUid(uid);
            clock.setEntertime(time);
            clock.setLeavetime(time);
            List<Vacate> vacate = vacateMapper.selectByUidAndTime(uid);
            if (vacate.size() != 0){
                clock.setCstatus(4);
                clock.setCflag(2);
                checkMapper.insertSelective(clock);
            } else {
                clock.setCstatus(3);
                clock.setCflag(1);
                checkMapper.insertSelective(clock);
                // 扣分相关操作
                makeScore(3, uid);
            }
        }

        // 查询未签退的人员并修改状态
        List<Clock> clocks = checkMapper.selectAllClockNoLeaveTime();
        for (Clock c : clocks) {
            int uid = c.getUid();
            c.setCstatus(2);
        }

        // 查询自己打卡生成的记录并判断状态并做扣分操作
        List<Clock> clocks1 = checkMapper.selectAllClockByFlag();
        for (Clock c : clocks1){
            int uid = c.getUid();
            switch (c.getCstatus()){
                case 1:
                    makeScore(1, uid);
                    break;
                case 2:
                    makeScore(2, uid);
                    break;
                case 3:
                    makeScore(3, uid);
                    break;
                case 4:
                    makeScore(4, uid);
                    break;
                default:
                    break;
            }
        }
        System.out.println("考勤情况遍历完成");
    }

    /**
     * 定时任务修改周一二四下班时间
     */
    @Scheduled(cron = "0 0 6 ? * MON,TUE,THU")
    @Async
    public void overTime(){
        Leavetime leavetime = new Leavetime();
        leavetime.setLid(1);
        leavetime.setLtime("20:50:00");
        leavetimeMapper.updateByPrimaryKey(leavetime);
        System.out.println("修改下班时间完成");
    }

    /**
     * 定时任务修改周三五下班时间
     */
    @Scheduled(cron = "0 0 6 ? * WED,FRI")
    @Async
    public void normalTime(){
        Leavetime leavetime = new Leavetime();
        leavetime.setLid(1);
        leavetime.setLtime("17:30:00");
        leavetimeMapper.updateByPrimaryKey(leavetime);
        System.out.println("修改下班时间完成");
    }

    // 扣分操作并添加扣分记录
    private void makeScore(Integer status, Integer uid){
        Score score = scoreMapper.selectByValue(status);
        History history = new History();
        history.setAid(uid);
        history.setOperatesorce(score.getScore());
        history.setReason(score.getScoredesc());
        history.setOperatetime(new Date());
        Account account = accountMapper.selectByPrimaryKey(uid);
        if (account.getAintegral() >= 0 && (account.getAintegral()+scoreMapper.selectByValue(status).getScore())>= 0){
            accountMapper.updateAintegralByUid(uid, status);
            history.setTotalchange(accountMapper.selectByPrimaryKey(uid).getAintegral());
            historyMapper.insertSelective(history);
        } else if ((account.getAintegral()+scoreMapper.selectByValue(status).getScore()) < 0) {
            account.setAintegral(0d);
            accountMapper.updateByPrimaryKeySelective(account);
            history.setTotalchange(account.getAintegral());
            historyMapper.insertSelective(history);
        }
    }

}
